import os

from logzero import logger
import pandas as pd

from server.app.cloud_ide.schema.roles.request.role_create_request import RoleCreateRequest
from server.app.cloud_ide.schema.tenant.request.tenant_create_request import TenantCreateRequest
from server.app.cloud_ide.schema.users.request.user_create_request import UserCreateRequest
from server.app.cloud_ide.schema.users.request.user_role_update_request import UserRoleUpdateRequest
from server.app.cloud_ide.service.role_service import RoleService
from server.app.cloud_ide.service.tenant_service import TenantService
from server.app.cloud_ide.service.user_service import UserService
from server.framework.core.database import SessionLocal, engine
from server.framework.utils.keycloak_manager import build_keycloak_admin
from server.framework.utils.kubernetes.kubernetes_client import KubernetesClient


def main() -> None:
    logger.info("初始化数据")

    kubernetes_client = KubernetesClient()
    nodes_info = kubernetes_client.list_node_info()
    allow_nodes = ','.join([x.node_name for x in nodes_info])
    default_tenant_name = 'MegaIDE'
    tenant_service = TenantService()
    tenant = tenant_service.get_tenant_by_name(default_tenant_name)
    if tenant is None:
        logger.warning(f'初始化默认租户[{default_tenant_name}]')
        tenant_service.create_tenant(TenantCreateRequest(
            name=default_tenant_name,
            max_cpu=4,
            max_memory=4,
            max_disk=20,
            allow_nodes=allow_nodes
        ))
    else:
        logger.info(f'默认租户[{default_tenant_name}]已存在')
    tenant = tenant_service.get_tenant_by_name(default_tenant_name)

    role_service = RoleService()
    admin_role = role_service.get_role_detail_by_name(tenant.id, 'admin')
    if admin_role is None:
        logger.warning('初始化默认角色[admin]')
        role_service.create_role(RoleCreateRequest(
            tenant_id=tenant.id,
            name='admin',
            max_cpu=4,
            max_memory=4,
            max_disk=20,
            allow_nodes=allow_nodes
        ))
    else:
        logger.info(f'默认角色[admin]已存在')
    admin_role = role_service.get_role_detail_by_name(tenant.id, 'admin')

    user_service = UserService()
    target_user = user_service.find_user_by_name('megalab')
    if target_user is None:
        logger.warning('初始化默认用户[megalab]')
        user_service.create_user(UserCreateRequest(
            username='megalab',
            email='core@etherfurnace.com',
            first_name='himouto',
            last_name='umaru',
            password='megalab'
        ))
    else:
        logger.info(f'默认角色[megalab]已存在')
    target_user = user_service.find_user_by_name('megalab')

    user_service.set_user_roles(UserRoleUpdateRequest(
        id=target_user.id,
        group_id=admin_role.id
    ))

    session = SessionLocal()
    init_data_path = os.path.join(os.path.dirname(__file__), "init_data")
    files = ['ide_registry.csv', 'ide_image.csv']
    for file in files:
        file_path = os.path.join(init_data_path, file)
        df = pd.read_csv(file_path, sep=",")
        logger.info(f"{file}  load successed")
        table_name = file.replace(".csv", "")
        df.to_sql(table_name, engine, if_exists="append", index=False)
    session.commit()
    session.close()

    logger.info("Initial data created")


if __name__ == "__main__":
    main()
